package com.example.musicdemo1.adapter

import android.graphics.drawable.Drawable
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.example.musicdemo1.R
import com.example.musicdemo1.model.Music

class RecommendMusicAdapter(private val musicList: List<Music>) :
    RecyclerView.Adapter<RecommendMusicAdapter.MusicViewHolder>() {

    inner class MusicViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val coverImage: ImageView = view.findViewById(R.id.albumCover)
        val titleText: TextView = view.findViewById(R.id.songTitle)
        val artistText: TextView = view.findViewById(R.id.artistName)

        init {
            // 设置itemView的宽度为屏幕宽度的1/3
            val displayMetrics = view.context.resources.displayMetrics
            val screenWidth = displayMetrics.widthPixels
            val itemWidth = screenWidth / 3
            view.layoutParams.width = itemWidth
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MusicViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_music, parent, false)
        return MusicViewHolder(view)
    }

    override fun onBindViewHolder(holder: MusicViewHolder, position: Int) {
        val music = musicList[position]
        holder.titleText.text = music.title
        // holder.artistText.text = music.artist  // 隐藏艺术家名称
        Glide.with(holder.coverImage)
            .load(music.albumCoverUrl)
            .error(R.drawable.ic_launcher_background)
            .placeholder(R.drawable.ic_launcher_background)
            .listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>,
                    isFirstResource: Boolean
                ): Boolean {
                    Log.e("RecommendAdapter", "图片加载失败: $model", e)
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable,
                    model: Any,
                    target: Target<Drawable>,
                    dataSource: DataSource,
                    isFirstResource: Boolean
                ): Boolean {
                    Log.d("RecommendAdapter", "图片加载成功: $model")
                    return false
                }
            })
            .into(holder.coverImage)
    }

    override fun getItemCount() = musicList.size
} 